//引入公共样式
require('../../assets/css/index.less')

//引入当前样式
require('./login.less')

//引入axios
let request = require('../../utils/request.js')

//引入dom.js
const dom = require('../../utils/dom.js')

//等dom加载完毕之后操作dom
window.onload = () => {
    //点击注册按钮
    dom.$('#submit').addEventListener('click', () => {
        let errMsg = ""
            //开始验证
            //手机号验证
        if (!/^1[3-9]\d{9}$/.test(dom.$('#phoneInp').value)) {
            errMsg = '手机号格式不正确'
        } else
        if (!/^\w{3,6}$/.test(dom.$('#pswInp').value)) {
            errMsg = '密码3-6位'
        } else {
            console.log('验证通过 可以发送请求')
                //发送登录请求
            request
                .post('/api/user/login', {
                    account: dom.$('#phoneInp').value,
                    password: dom.$('#pswInp').value,
                })
                .then(res => {
                    console.log('res.data :>> ', res.data)
                        //1 解构数据
                    let { errno, data } = res.data
                        //2 判断
                    if (errno === 0) {
                        //3 处理数据
                        localStorage.setItem('token', 'Bearer ' + data.token)
                        alert('登录成功')
                            //4 跳转首页
                        window.location.href = 'home.html'
                    }
                })
                .catch(err => {
                    console.log('err :>> ', err)
                })
        }
        if (errMsg) {
            alert(errMsg)
        }
    })

}